package com.nulldev.util.web.flexibleKit.scfk.io.streams;

import java.util.Collections;
import java.util.Map;

import com.nulldev.util.data.Arrays.maps.FastMaps;
import com.nulldev.util.io.IOUtils;
import com.nulldev.util.web.flexibleKit.scfk.io.keepalive.ProtocolKeepAlive;

public class StreamManager {

	private static final Map<String, Stream> streams = FastMaps.map(ProtocolKeepAlive.MAXIMUM_GLOBAL_USE_COUNT);

	public static boolean hasCachedStreamFor(final String host) {
		if (host == null || host.isEmpty())
			return false;
		return streams.containsKey(host);
	}

	public static boolean tryCache(final String host, final Stream s) {
		if (streams.containsKey(host))
			return false;
		return streams.put(host, s) == null;
	}

	public static boolean removeFromCache(final String host) {
		if (!streams.containsKey(host))
			return false;
		if (streams.get(host).shouldKeepAlive())
			return false;
		return streams.remove(host) != null;
	}

	public static Stream tryFetch(final String host) {
		if (!streams.containsKey(host))
			return null;
		final Stream s = streams.get(host);
		if (s.isInUse() || s.isClosed())
			return null;
		if (s.getStreamUseCount() > ProtocolKeepAlive.MAXIMUM_GLOBAL_USE_COUNT) {
			streams.remove(host);
			IOUtils.closeQuietly(s);
			return null;
		}
		return s.use();
	}

	public static Map<String, Stream> streams() {
		return Collections.unmodifiableMap(streams);
	}
}
